package com.inei.eea2014.controller.activity;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import com.inei.eea2014.R;
import com.inei.eea2014.controller.EntrevistaController;
import com.inei.eea2014.controller.MarcoController;
import com.inei.eea2014.controller.OpcionesController;
import com.inei.eea2014.model.entity.Entrevista;
import com.inei.eea2014.model.entity.Marco;
import com.inei.eea2014.model.entity.Resultado;
import com.inei.eea2014.tools.Mensaje;

import android.app.Activity;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class Menu_Activity extends Activity {

	// componentes
	private DrawerLayout mDrawerLayout;
	private ActionBarDrawerToggle mDrawerToggle;
	private ListView mDrawerList;

	// variables
	private String RUC;
	private String USUARIO;
	private LocationManager locManager;
	private LocationListener locListener;
	private String[] items;
	private String[] titulos;
	private String titulo;
	private int cap;
	private Caratula_Fragment car;
	private CapituloI_Fragment cap01;
	private CapituloII_Fragment cap02;
	private CapituloIII_Fragment cap03;
	private CapituloIV_Fragment cap04;
	private Mensaje m;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_menu);

		m = new Mensaje(getApplicationContext());

		IniciarComponentes();

		CargarDatos();

		AgregarEventos();

		if (savedInstanceState == null) {
			SelectItem(0);
			cap = 0;
		}

		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(titulo);
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle("SELECCIONAR CAPITULO");
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_cap, menu);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (mDrawerList.isShown()) {
			menu.setGroupVisible(R.id.gpMenu, false);
		} else {
			menu.setGroupVisible(R.id.gpMenu, true);
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		switch (item.getItemId()) {

		case R.id.mnTerminar:
			CrearMenuR();
			break;

		case R.id.mnValidar:
			Validar();
			break;

		case R.id.mnGuardar:
			GuardarDatos();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public void setTitle(CharSequence titulo) {
		getActionBar().setTitle(titulo);
	}

	@Override
	public void onBackPressed() {
	}

	private void IniciarComponentes() {
		mDrawerLayout = (DrawerLayout) findViewById(R.id.menu);

		mDrawerList = (ListView) findViewById(R.id.lvMenu);

		items = getResources().getStringArray(R.array.menu_item);
		mDrawerList.setAdapter(new ArrayAdapter<String>(this,
				R.layout.menu_item, items));

		titulos = getResources().getStringArray(R.array.titulo_item);
	}

	private void CargarDatos() {
		RUC = getIntent().getExtras().getString("RUC");
		USUARIO = getIntent().getExtras().getString("USUARIO");

		IniciarBusqueda();
	}

	private void IniciarBusqueda() {
		locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		Location location = locManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		locListener = new LocationListener() {

			@Override
			public void onStatusChanged(String provider, int status,
					Bundle extras) {
			}

			@Override
			public void onProviderEnabled(String provider) {
				m.Exito("Proveedor GPS Activado");
			}

			@Override
			public void onProviderDisabled(String provider) {
				m.Error("Proveedor GPS Desactivado");
			}

			@Override
			public void onLocationChanged(Location location) {
				BuscarPuntos(location);
			}
		};

		locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000,
				1000, locListener);

	}

	private void BuscarPuntos(Location loc) {
		if (loc != null) {

			EntrevistaController entCon = new EntrevistaController(
					getApplicationContext());
			Entrevista ent = new Entrevista(RUC, USUARIO);
			ent.setNRO_ENT(entCon.EntrevistaTotal(ent));

			ent = entCon.EntrevistaBuscar(ent);
			ent.setGPS_LAT(loc.getLatitude() + "");
			ent.setGPS_LON(loc.getLongitude() + "");
			Log.i("LAT_I", loc.getLatitude() + "");
			Log.i("LON_I", loc.getLongitude() + "");

			if (entCon.EntrevistaModificar(ent) > 0) {
				m.Exito("SE OBTUVIERON LOS PUNTOS");

				locManager.removeUpdates(locListener);
			}
		}
	}

	private void AgregarEventos() {
		mDrawerList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int pos,
					long id) {
				SelectItem(pos);
			}
		});
	}

	private void SelectItem(int pos) {
		titulo = titulos[pos];
		setTitle(titulo);
		Fragment fragment = null;
		switch (pos) {
		case 0:
			car = new Caratula_Fragment();
			fragment = car;
			break;
		case 1:
			cap01 = new CapituloI_Fragment();
			fragment = cap01;
			break;
		case 2:
			cap02 = new CapituloII_Fragment();
			fragment = cap02;
			break;
		case 3:
			cap03 = new CapituloIII_Fragment();
			fragment = cap03;
			break;
		case 4:
			cap04 = new CapituloIV_Fragment();
			fragment = cap04;
			break;

		default:
			break;
		}
		FragmentManager fragmentManager;
		Bundle datos;
		datos = new Bundle();
		datos.putString("RUC", RUC);
		datos.putString("USUARIO", USUARIO);
		fragment.setArguments(datos);
		fragmentManager = getFragmentManager();
		fragmentManager.beginTransaction()
				.replace(R.id.contenido_menu, fragment).commit();

		mDrawerList.setItemChecked(pos, true);
		mDrawerLayout.closeDrawer(mDrawerList);
		cap = pos;
	}

	private void CrearMenuR() {
		final Dialog dialogoR = new Dialog(this,
				R.style.Theme_Dialog_Translucent);
		dialogoR.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialogoR.setContentView(R.layout.dialog_terminar);

		TextView titulo = (TextView) dialogoR.findViewById(R.id.titulo);
		titulo.setText("Evaluador");

		final TimePicker tp1R = (TimePicker) dialogoR.findViewById(R.id.tp1);
		tp1R.setIs24HourView(true);

		final DatePicker dp1R = (DatePicker) dialogoR.findViewById(R.id.dp1);

		final Spinner spOpcionesR = (Spinner) dialogoR
				.findViewById(R.id.spOpciones);

		final EditText etO = (EditText) dialogoR.findViewById(R.id.etO);
		etO.setVisibility(View.GONE);

		OpcionesController conRes = new OpcionesController(
				getApplicationContext());
		List<Resultado> opciones = conRes.ResultadoObtenerTodo();
		Resultado res = new Resultado();
		res.setCODIGO("0");
		res.setNOMRESULTADO("Seleccionar resultado");
		opciones.add(0, res);
		spOpcionesR.setAdapter(new ArrayAdapter<Resultado>(this,
				android.R.layout.simple_spinner_dropdown_item, opciones));

		spOpcionesR.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> a, View v, int pos,
					long id) {
				switch (pos) {
				case 8:
					etO.setVisibility(View.VISIBLE);
					break;

				default:
					etO.setText("");
					etO.setVisibility(View.GONE);
					break;
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

		Button btn1 = (Button) dialogoR.findViewById(R.id.btn1);

		btn1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				EntrevistaController entCon = new EntrevistaController(
						getApplicationContext());
				Entrevista o = new Entrevista();

				o.setRUC(RUC);
				o.setUSUARIO(USUARIO);
				o.setNRO_ENT(entCon.EntrevistaTotal(o));
				o = entCon.EntrevistaBuscar(o);

				SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
				Calendar c = Calendar.getInstance();
				String h = sdf.format(c.getTime());
				String full[] = h.split(" ");
				o.setC0024_000_03_T(full[1]);

				o.setC0024_000_04_T(((Resultado) spOpcionesR.getSelectedItem())
						.getCODIGO());
				SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");
				int day = dp1R.getDayOfMonth();
				int month = dp1R.getMonth();
				int year = dp1R.getYear();
				Calendar c2 = Calendar.getInstance();
				c2.set(year, month, day);
				o.setC0024_000_05_T(sdf2.format(c2.getTime()));
				o.setC0024_000_06_T((tp1R.getCurrentHour() < 10 ? ("0" + tp1R
						.getCurrentHour()) : tp1R.getCurrentHour())
						+ ":"
						+ (tp1R.getCurrentMinute() < 10 ? ("0" + tp1R
								.getCurrentMinute()) : tp1R.getCurrentMinute()));

				MarcoController marCon = new MarcoController(
						getApplicationContext());
				Marco mar = new Marco(RUC, USUARIO);
				mar = marCon.MarcoObtener(mar);
				if (spOpcionesR.getSelectedItemPosition() != 0) {
					if (spOpcionesR.getSelectedItemPosition() != 1) {
						if (entCon.EntrevistaModificar(o) > 0) {
							mar.setFINALIZADO("0");
							marCon.MarcoActualizar(mar);

							m.Exito("TERMINADO");
							locManager.removeUpdates(locListener);

							Intent ir_marco = new Intent(
									getApplicationContext(),
									Marco_Activity.class);
							Bundle datos = new Bundle();
							datos.putString("RUC", RUC);
							datos.putString("USUARIO", USUARIO);
							ir_marco.putExtras(datos);
							startActivity(ir_marco);
							finish();
						} else {
							m.Error("ERROR AL TERMINAR");
						}
						invalidateOptionsMenu();
						dialogoR.dismiss();
					} else {
						if (mar.getVALIDADO().equals("2")) {
							if (entCon.EntrevistaModificar(o) > 0) {
								mar.setFINALIZADO("1");
								marCon.MarcoActualizar(mar);

								m.Exito("TERMINADO");
								locManager.removeUpdates(locListener);

								Intent ir_marco = new Intent(
										getApplicationContext(),
										Marco_Activity.class);
								Bundle datos = new Bundle();
								datos.putString("RUC", RUC);
								datos.putString("USUARIO", USUARIO);
								ir_marco.putExtras(datos);
								startActivity(ir_marco);
								finish();
							} else {
								m.Error("ERROR AL TERMINAR");
							}
							invalidateOptionsMenu();
							dialogoR.dismiss();
						} else {
							m.Error("NO PUEDE TERMINAR, TIENE ERRORES SIN JUSTIFICAR");
						}
					}
				} else {
					m.Error("DEBE SELECCIONAR UN RESULTADO");
				}
			}
		});

		Button btn2 = (Button) dialogoR.findViewById(R.id.btn2);

		btn2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialogoR.dismiss();
			}
		});

		dialogoR.show();

	}

	private void Validar() {
		switch (cap) {
		case 0:
			car.ValidarCap();
			break;

		case 1:
			cap01.ValidarCap();
			break;

		case 2:
			cap02.ValidarCap();
			break;

		case 3:
			cap03.ValidarCap();
			break;

		case 4:
			cap04.ValidarCap();
			break;

		default:
			break;
		}
	}

	private void GuardarDatos() {
		switch (cap) {
		case 0:
			car.GuardarCap();
			break;

		case 1:
			cap01.GuardarCap();
			break;

		case 2:
			cap02.GuardarCap();
			break;

		case 3:
			cap03.GuardarCap();
			break;

		case 4:
			cap04.GuardarCap();
			break;

		default:
			break;
		}
	}
}
